var SEP = "\t";
var BASE = "main.php";

function newLocation(params) {
  var loc = BASE;
  var sep = "?";
  if (host) {
    loc += sep + "host=" + host;
    sep = "&";
  }
  if (params) {
    loc += sep + params;
  }
  return loc;
}

function onLoad() {
  if (artists) {
    loadArtists();
  } else if (albums) {
    loadAlbums();
  } else if (songs) {
    loadSongs();
  } else if (controls) {
    loadControls();
  } else if (artist && album) {
    loadAlbum(artist,album);
  } else if (artist) {
    loadArtist(artist);
  } else {
    loadDefault();
    loadResetHost();
  }
}
    
function loadArtists() {
  sendMsg('GetArtists',"showArtists", {  });
}
    
function loadAlbums() {
  addTitle("albums");
}
    
function loadSongs() {
  addTitle("songs");
}
    
function loadAlbum(artist,album) {
  sendMsg('GetTracks',"showTracks", {  artist:artist, name:album });
}
    
function loadArtist(artist) {
  sendMsg('GetAlbums',"showAlbums", {  name:artist });
}
    
function loadDefault() {
  newLi('Artists','artists');
  newLi('Controls','controls');
}

function loadControls() {
  addTitle("controls");
  newLi('Back').onclick = itunesBack;
  newLi('Stop').onclick = itunesStop;
  newLi('Play').onclick = itunesPlay;
  newLi('Next').onclick = itunesNext;
}

function showArtists(msg) {
  addTitle("artists");
  var vs = msg.split(SEP);
  for (var i=0; i<vs.length; i++) {
    var artist = vs[i];
    if (!artist) continue;
    newLi(artist,'artist=' + escape(artist));
  }
}

function showAlbums(msg) {
  var vs = msg.split(SEP);
  var artist = vs[0];
  addTitle(artist);
  for (var i=1; i<vs.length; i++) {
    var album = vs[i];
    if (!album) continue;
    newLi(album, 'artist=' + escape(artist) + "&album=" + escape(album));
  }
}

function addTitle(title) {
  document.title = title;
  $("title").innerHTML += " :: " + title;
}

function showTracks(msg) {
  var vs = msg.split(SEP);
  var artist = vs[0];
  var album = vs[1];
  addTitle(artist + " // " + album);
  for (var i=2; i<vs.length; i++) {
    var name = vs[i];
    if (!name) continue;
    var li = newLi(name);
    li.onclick = newPlayFunction(name);
  }
}

function newPlayFunction(name) {
  var _name = name;
  return function() {itunesPlayTrack(_name);};
}

